//
//  GPPhotoViewController.m
//  GP
//
//  Created by Sally on 16/7/30.
//  Copyright © 2016年 Sally. All rights reserved.
//
#define GP_SCREEN_WIDTH  ([[UIScreen mainScreen] bounds].size.width)
#define GP_SCREEN_HEIGHT  ([[UIScreen mainScreen] bounds].size.height)
#import "GPPhotoViewController.h"
#import "GPPhotoCollectionViewCell.h"
#import "LYPhotoTools.h"
//#import "GPGifViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface GPPhotoViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>


@property (strong, nonatomic) UICollectionView *phtotCollectionView;
@property (strong, nonatomic) NSMutableArray *imagesArr;
@end
static NSString *cellIdentifier = @"gpPhtotCollectionViewCell";

@implementation GPPhotoViewController{
    NSMutableArray *selectArray;//保存那些被选中
    NSInteger currentSelectIndex;//当前选中index
    NSMutableArray *saveImageArray;//   被选中的图片
    NSMutableArray *assetArray;     //保存asset
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    UICollectionViewFlowLayout *layoutFlow = [[UICollectionViewFlowLayout alloc] init];
//    self.phtotCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-50) collectionViewLayout:layoutFlow];
//    self.phtotCollectionView.dataSource = self;
//    self.phtotCollectionView.delegate = self;
//    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0,self.view.frame.size.height-50, self.view.frame.size.width, 50)];
//    [btn setTitle:@"确认" forState:UIControlStateNormal];
//    [btn addTarget:self action:@selector(clickSureAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.phtotCollectionView registerClass:[GPPhotoCollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
//    self.view.backgroundColor = [UIColor whiteColor];
//    self.imagesArr = [NSMutableArray array];
//    selectArray = [NSMutableArray array];
//    saveImageArray = [NSMutableArray array];
//    assetArray = [NSMutableArray array];
//    [self preparePhotos];
    // Do any additional setup after loading the view.
}

- (void)preparePhotos{
    __weak typeof(self) weakSelf = self;
    [self.assetGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if (result == nil) {
            return;
        }
        [assetArray addObject:result];
        [weakSelf.imagesArr addObject:[UIImage imageWithCGImage:result.thumbnail]];
        [selectArray addObject:@"0"];

    }];
    
        [self.phtotCollectionView reloadData];

}

- (void)initView{

}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.allOfImage;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GPPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.tag = indexPath.row;
    [cell setDataInfo:self.imagesArr[indexPath.row] index:[selectArray[indexPath.row] integerValue] currentIndex:currentSelectIndex];
    __weak typeof(self) weakSelf = self;
    cell.SelectBlock = ^(NSInteger currentIndex,NSInteger tag){
        if (currentIndex==0) {
            //取消选择
            [weakSelf cancelSelectImage:currentIndex withTag:tag];
        }else{
            [weakSelf selectImageSuccess:currentIndex withTag:tag];
        }
    };
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = (GP_SCREEN_WIDTH-6)/4.0;
    return CGSizeMake(width, width);
}

- (void)selectImageSuccess:(NSInteger)currentIndex withTag:(NSInteger)tag{
    currentSelectIndex = currentIndex;
    [selectArray replaceObjectAtIndex:tag withObject:[NSString stringWithFormat:@"%ld",currentIndex]];
    [saveImageArray addObject:[self selectedAssets:assetArray[tag]]];
    [self.phtotCollectionView reloadData];
}

- (void)cancelSelectImage:(NSInteger)currentIndex withTag:(NSInteger)tag{
    currentSelectIndex -=1;
    NSInteger oldIndex = [selectArray[tag] integerValue];
    [selectArray replaceObjectAtIndex:tag withObject:[NSString stringWithFormat:@"%ld",currentIndex]];
    for (int i =0; i<selectArray.count; i++) {
        NSInteger index = [selectArray[i] integerValue];
        if (index!=0&&index>oldIndex) {
            [selectArray replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%ld",index-1]];
        }
    }
    [saveImageArray removeObjectAtIndex:currentSelectIndex];
    [self.phtotCollectionView reloadData];
    
}

- (IBAction)clickSureAction:(id)sender {
//    GPGifViewController *gif = [[GPGifViewController alloc] init];
//    gif.content = saveImageArray;
//    [self.navigationController pushViewController:gif animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (UIImage *)selectedAssets:(ALAsset *)asset
{

        id obj = [asset valueForProperty:ALAssetPropertyType];
        if (!obj) {
            return nil;
        }
        NSMutableDictionary *workingDictionary = [[NSMutableDictionary alloc] init];
        
        CLLocation* wgs84Location = [asset valueForProperty:ALAssetPropertyLocation];
        if (wgs84Location) {
            [workingDictionary setObject:wgs84Location forKey:ALAssetPropertyLocation];
        }
        
        [workingDictionary setObject:obj forKey:UIImagePickerControllerMediaType];
        
        //This method returns nil for assets from a shared photo stream that are not yet available locally. If the asset becomes available in the future, an ALAssetsLibraryChangedNotification notification is posted.
        ALAssetRepresentation *assetRep = [asset defaultRepresentation];
        
        if(assetRep != nil) {
                CGImageRef imgRef = nil;
                //defaultRepresentation returns image as it appears in photo picker, rotated and sized,
                //so use UIImageOrientationUp when creating our image below.
                UIImageOrientation orientation = UIImageOrientationUp;
                
                imgRef = [assetRep fullResolutionImage];
                orientation = [assetRep orientation];
            
                UIImage *img = [UIImage imageWithCGImage:imgRef
                                                   scale:1.0f
                                             orientation:orientation];
            return img;
        }
    return nil;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
